﻿ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 using System.Windows.Threading;
 using RiskMan.Config;
 using RiskMan.DataClass.Models.Quik;
 using RiskMan.DataClass.Models.RM;
 using RiskMan.Models;
 using RiskMan.Providers;
 using XlDde;
using NDde.Server;
 using RiskMan.DataClass.Models;
using System.Collections.ObjectModel;
 using RiskMan.Views.RiskManager;

namespace RiskMan.DataClass
{
    public partial class Data
    {
        private DdeProvider _ddeServer;

        public ObservableCollection<CurrentParamModel> CurrentList = new ObservableCollection<CurrentParamModel>();
        public List<DealModel> DealList = new List<DealModel>( );
        public List<EmitentLimitModel> EmitentLimiteList = new List<EmitentLimitModel>( );
        public List<StopOrderModel> StopOrderList = new List<StopOrderModel>( );
        public ObservableCollection<OrderModel> OrderList = new ObservableCollection<OrderModel>();
        public ObservableCollection<LimitByAccountModel> LimitebyAccount = new ObservableCollection<LimitByAccountModel>( );
        public List<PositionToClientAccountModel> FortsPositionsList = new List<PositionToClientAccountModel>();
        public List<PortfelModel> Portfel = new List<PortfelModel>( );
        public List<LimitByCashModel> LimiteByMoneySredstva = new List<LimitByCashModel>( );
        public ObservableCollection<MMVBComisClass> MmvbComisList = new ObservableCollection<MMVBComisClass>( );
        public Dispatcher Dispatcher = null;

        public ObservableCollection<ModuleInvestorModel> RmInvestorItems = new ObservableCollection<ModuleInvestorModel>( );

        public QuikItems T2QItems = new QuikItems( );
        
        #region data for StopView

        /// <summary>
        /// массив стопов пользователя
        /// </summary>
        public ObservableCollection<StopListModel> StopList = new ObservableCollection<StopListModel>( );

        /// <summary>
        /// массив лимитов по бумагам
        /// </summary>
        public ObservableCollection<ModuleLimitStockModel> LimitStockList = new ObservableCollection<ModuleLimitStockModel>();
        public ObservableCollection<LimitMoneyAndDealsModel> LimitMoneyAndDealsList = new ObservableCollection<LimitMoneyAndDealsModel>();

        public List<OrderModel> TakeOrderList = new List<OrderModel>( );
        /// <summary>
        /// сделки по которым устанавливается стоп-лосс
        /// </summary>
        public List<DealModel> DealSOrderList = new List<DealModel>( );

        /// <summary>
        /// стоп-лосс выставленный по сделке
        /// </summary>
        public List<StopOrderModel> StopLossOrderList = new List<StopOrderModel>( );

        #endregion

        #region data for RiskManagerView

        /// <summary>
        /// массив настроеных счетов для риск манагера
        /// </summary>
        public ObservableCollection<RmItem> RMItems = new ObservableCollection<RmItem>( );

        /// <summary>
        /// массив расчитаной прибыли по запущеным в обработку счетам
        /// </summary>
        public AccountLimiteItems ACLimiteItems = new AccountLimiteItems( );

        /// <summary>
        /// массив выставленных блокирующих заявок 
        /// в риск менеджере
        /// </summary>
        //public OBlockingItems OrderBlockingItems = new OBlockingItems( );
        //public SOBlockingItems StopOrderBlockingItems = new SOBlockingItems( );

        #endregion

        public Data ( )
        {
            _ddeServer = new DdeProvider();
            _ddeServer.Connect( );
        }

        public double GetEnterPrice ( string seccode, string clientcode, string account, double currpos )
        {
            double result = 0;

            if ( currpos > 0 )
                for ( int i = DealList.Count - 1; i >= 0; i-- )
                    if ( DealList [ i ].Account == account &&
                        DealList [ i ].ClientCode == clientcode &&
                        DealList [ i ].Seccode == seccode &&
                        DealList [ i ].Operation == cfg.Buy )
                        return DealList [ i ].Price;

            if ( currpos < 0 )
                for ( int i = DealList.Count - 1; i >= 0; i-- )
                    if ( DealList [ i ].Account == account &&
                        DealList [ i ].ClientCode == clientcode &&
                        DealList [ i ].Seccode == seccode &&
                        DealList [ i ].Operation == cfg.Sell )
                        return DealList [ i ].Price;

            return result;
        }

        public double GetSLActive ( string seccode, string clientcode, string account, double currpos )
        {
            double result = 0;

            if ( currpos > 0 )
                for ( int i = StopOrderList.Count - 1; i >= 0; i-- )
                    if ( StopOrderList [ i ].TradeAccount == account &&
                        StopOrderList [ i ].ClientCode == clientcode &&
                        StopOrderList [ i ].Seccode == seccode &&
                        StopOrderList [ i ].Operation == cfg.Sell )
                        return StopOrderList [ i ].StopPrice;

            if ( currpos < 0 )
                for ( int i = StopOrderList.Count - 1; i >= 0; i-- )
                    if ( StopOrderList [ i ].TradeAccount == account &&
                        StopOrderList [ i ].ClientCode == clientcode &&
                        StopOrderList [ i ].Seccode == seccode &&
                        StopOrderList [ i ].Operation == cfg.Buy )
                        return StopOrderList [ i ].StopPrice;

            return result;
        }

        public bool GetTypeAccount ( string clientCode )
        {
            for ( int i = 0; i < Portfel.Count; i++ )
            {
                if ( Portfel [ i ].CodeClient == clientCode )
                    return false;
            }
            return true;
        }

        public double GetTypeAccountMoney ( string account, string clientcode )
        {
            for ( int i = 0; i < Portfel.Count; i++ )
            {
                if ( Portfel [ i ].Firm != "NB0253900000" )
                {
                    if ( Portfel [ i ].SrochAccount == account )
                        return Portfel [ i ].EnterSredstva;
                    if ( Portfel [ i ].CodeClient == clientcode )
                        return Portfel [ i ].EnterSredstva;
                }
            }
            return 0;
        }

        public double GetMoney ( string clientcode )
        {
            for ( int i = 0; i < LimiteByMoneySredstva.Count; i++ )
            {
                if ( LimiteByMoneySredstva [ i ].Valute == "SUR" )
                {
                    if ( LimiteByMoneySredstva [ i ].CodeClient == clientcode && LimiteByMoneySredstva [ i ].Group == "GLSP" )
                        return LimiteByMoneySredstva [ i ].Dostupno;

                    if ( LimiteByMoneySredstva [ i ].CodeClient == clientcode && LimiteByMoneySredstva [ i ].Group == "EQTV" )
                        return LimiteByMoneySredstva [ i ].Dostupno;
                }
            }
            return 0;
        }

        public List<string> ListPath = new List<string>( );

        public String GetAccount ( string clientcode )
        {
            for ( int i = 0; i < T2QItems.Count; i++ )
            {
                for ( int j = 0; j < T2QItems [ i ].TradeList.Count; j++ )
                    if ( clientcode == T2QItems [ i ].TradeList [ j ].ClientCode )
                        return T2QItems [ i ].TradeList [ j ].Account;
            }
            return "";
        }

        public StopOrderModel GetData ( StopOrderModel stopOrderModel )
        {
            for ( int i = 0; i < StopOrderList.Count; i++ )
            {
                if ( StopOrderList [ i ].TID == stopOrderModel.TID )
                    stopOrderModel = StopOrderList [ i ];
            }
            return stopOrderModel;
        }

        public double GetPriceClose ( string seccode )
        {
            for ( int i = 0; i < CurrentList.Count; i++ )
            {
                if ( CurrentList [ i ].Seccode == seccode )
                    return Math.Floor( CurrentList [ i ].ClosePrice * GetLots( seccode ) / 2 ) / GetLots( seccode );
            }
            return 0;
        }

        public double GetDostupnoBalance ( string _clientCode )
        {
            double result = 0;

            for ( int i = 0; i < Portfel.Count; i++ )
            {
                if ( Portfel [ i ].CodeClient == _clientCode )
                    return Portfel [ i ].OnBuy;
            }

            return result;
        }

        public double GetDostupnoBalance ( AccountLimiteItem item )
        {
            double result = 0;

            for ( int i = 0; i < Portfel.Count; i++ )
            {
                if ( Portfel [ i ].CodeClient == item.ClientCode )
                    return Portfel [ i ].OnBuy;
            }

            return result;
        }

        internal double GetLaverage ( string clientcode )
        {
            for ( int i = 0; i < Portfel.Count; i++ )
            {
                if ( Portfel [ i ].CodeClient == clientcode )
                    return Portfel [ i ].Laverage + 1;
            }
            return 1;
        }

        //internal char GetOperation ( AccountLimiteItem item )
        //{
        //    if ( item.Account == item.ClientCode )
        //    {
        //        for ( int i = 0; i < OrderBlockingItems.Count; i++ )
        //        {
        //            if ( OrderBlockingItems [ i ].Account == item.Account &&
        //                OrderBlockingItems [ i ].ClientCode == item.ClientCode &&
        //                OrderBlockingItems [ i ].Status == cfg.Active
        //               )
        //            {
        //                return OrderBlockingItems [ i ].Operation == cfg.Buy ? 'B' : 'S';
        //            }
        //        }
        //    }
        //    else
        //    {
        //        for ( int i = 0; i < StopOrderBlockingItems.Count; i++ )
        //        {
        //            if ( StopOrderBlockingItems [ i ].TradeAccount == item.Account &&
        //                StopOrderBlockingItems [ i ].ClientCode == item.ClientCode &&
        //                StopOrderBlockingItems [ i ].Status == cfg.Active
        //               )
        //            {
        //                return StopOrderBlockingItems [ i ].Operation == cfg.Buy ? 'B' : 'S';
        //            }
        //        }
        //    }
        //    return 'B';
        //}

        internal void Clear ( )
        {

            CurrentList = new ObservableCollection<CurrentParamModel>();
            DealList = new List<DealModel>( );
            EmitentLimiteList = new List<EmitentLimitModel>( );
            FortsPositionsList = new List<PositionToClientAccountModel>();
            StopOrderList = new List<StopOrderModel>( );
            OrderList = new ObservableCollection<OrderModel>();
            LimitebyAccount = new ObservableCollection<LimitByAccountModel>( );
            Portfel = new List<PortfelModel>( );
            LimiteByMoneySredstva = new List<LimitByCashModel>( );


            //for ( int i = 0; i < OrderBlockingItems.Count; i++ )
            //{
            //    var term = MainWindow.StaticRiskMan.Terminals;

            //    if ( OrderBlockingItems [ i ].Status == cfg.Active )
            //    {
            //        term.CancelOrder
            //        (
            //            OrderBlockingItems [ i ].Number,
            //            OrderBlockingItems [ i ].Seccode,
            //            GetClasscode( OrderBlockingItems [ i ].Seccode ),
            //            OrderBlockingItems [ i ].Account,
            //            OrderBlockingItems [ i ].ClientCode
            //        );
            //    }
            //}
            //OrderBlockingItems = new OBlockingItems( );

            //for ( int i = 0; i < StopOrderBlockingItems.Count; i++ )
            //{
            //    var term = MainWindow.StaticRiskMan.Terminals;

            //    if ( StopOrderBlockingItems [ i ].Status == cfg.Active )
            //    {
            //        term.CancelStopOrder
            //        (
            //            StopOrderBlockingItems [ i ].Number,
            //            StopOrderBlockingItems [ i ].Seccode,
            //            GetClasscode( StopOrderBlockingItems [ i ].Seccode ),
            //            StopOrderBlockingItems [ i ].TradeAccount,
            //            StopOrderBlockingItems [ i ].ClientCode
            //        );
            //    }
            //}
            //StopOrderBlockingItems = new SOBlockingItems( );
        }

        internal double GetStepPrice ( string seccode )
        {
            for ( int i = 0; i < CurrentList.Count; i++ )
            {
                if ( CurrentList [ i ].Seccode == seccode )
                {
                    return CurrentList [ i ].StepPrice;
                }
            }
            return 0;
        }

        /// <summary>
        /// Стоимость шага цены
        /// </summary>
        /// <param name="seccode"></param>
        /// <returns></returns>
        internal double GetStepPricet(string seccode)
        {
            for (int i = 0; i < CurrentList.Count; i++)
            {
                if (CurrentList[i].Seccode == seccode)
                {
                    return CurrentList[i].StepPricet;
                }
            }
            return 0;
        }

        internal List<OrderModel> GetOrderList ( string account, string clientcode )
        {
            List<OrderModel> result = new List<OrderModel>( );

            for ( int i = 0; i < OrderList.Count; i++ )
            {
                if ( OrderList [ i ].Account == account &&
                     OrderList [ i ].ClientCode == clientcode &&
                     OrderList [ i ].Status == cfg.Active )
                {
                    result.Add( OrderList [ i ] );
                }
            }

            return result;
        }

        internal List<OrderModel> GetOrderListAll(string account, string clientcode)
        {
            List<OrderModel> result = new List<OrderModel>();

            for (int i = 0; i < OrderList.Count; i++)
            {
                if (OrderList[i].Account == account &&
                     OrderList[i].ClientCode == clientcode)
                {
                    result.Add(OrderList[i]);
                }
            }

            return result;
        }

        internal List<StopOrderModel> GetStopOrderList ( string account, string clientcode )
        {
            List<StopOrderModel> result = new List<StopOrderModel>( );

            for ( int i = 0; i < StopOrderList.Count; i++ )
            {
                if ( StopOrderList [ i ].TradeAccount == account &&
                     StopOrderList [ i ].ClientCode == clientcode &&
                     StopOrderList [ i ].Status == cfg.Active )
                {
                    result.Add( StopOrderList [ i ] );
                }
            }

            return result;
        }
    }
}